package com.zmy.xcx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmy.xcx.dao.entity.HyperglycemiaMedicationDO;
import com.zmy.xcx.dao.mapper.HyperglycemiaMedicationMapper;
import com.zmy.xcx.dto.HyperglycemiaMedicationDTO;
import com.zmy.xcx.service.HyperglycemiaMedicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class HyperglycemiaMedicationServiceImpl extends ServiceImpl<HyperglycemiaMedicationMapper, HyperglycemiaMedicationDO> implements HyperglycemiaMedicationService {

    private static final AtomicInteger count = new AtomicInteger(0);

    @Override
    public List<HyperglycemiaMedicationDO> listHyperglycemiaMedication(HyperglycemiaMedicationDTO hyperglycemiaMedicationDTO) {
        LambdaQueryWrapper<HyperglycemiaMedicationDO> lambdaQueryWrapper = Wrappers.lambdaQuery(HyperglycemiaMedicationDO.class)
                .like(StrUtil.isNotBlank(hyperglycemiaMedicationDTO.getDrugName()), HyperglycemiaMedicationDO::getDrugName, hyperglycemiaMedicationDTO.getDrugName())
                .like(StrUtil.isNotBlank(hyperglycemiaMedicationDTO.getType()), HyperglycemiaMedicationDO::getType, hyperglycemiaMedicationDTO.getIsRx())
                .eq(ObjectUtil.isNotNull(hyperglycemiaMedicationDTO.getIsRx()), HyperglycemiaMedicationDO::getIsRx, hyperglycemiaMedicationDTO.getIsRx())
                .like(StrUtil.isNotBlank(hyperglycemiaMedicationDTO.getSource()), HyperglycemiaMedicationDO::getSource, hyperglycemiaMedicationDTO.getSource());
        return baseMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public void incrementPageView(Integer id) {
        count.incrementAndGet();
        //将点击量持久化到数据库
        LambdaUpdateWrapper<HyperglycemiaMedicationDO> lambdaUpdateWrapper = Wrappers.lambdaUpdate(HyperglycemiaMedicationDO.class)
                .eq(HyperglycemiaMedicationDO::getId, id)
                .setSql("page_view = page_view + " + count.get());
        update(lambdaUpdateWrapper);
        count.set(0);
    }

}
